package com.centriole.service.workflow.service.impl;

import com.centriole.service.workflow.dao.FunctionMapper;
import com.centriole.service.workflow.entity.Function;
import com.centriole.service.workflow.enums.StateType;
import com.centriole.service.workflow.service.FunctionService;
import com.centriole.service.workflow.util.CommonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class FunctionServiceImpl implements FunctionService {
	@Resource
	private FunctionMapper functionMapper;
	public void insertOrEdit(Function function) {
		//字段检查
		checkFunction(function);
		
		if(CommonUtil.isEmpty(function.getId())){
			function.setId(CommonUtil.getUuid());
			function.setState(StateType.NORMAL.statusCode());
			String creatorId = StringUtils.isBlank(function.getCreatorId()) ? "default" : function.getCreatorId();
			function.setCreatorId( creatorId );
			function.setModifierId( creatorId  );
			function.setCreateDate(new Date());
			functionMapper.insert(function);
		}else{
			functionMapper.edit(function);
		}
	}

	public List<Function> select(String name) {
		if(null == name)
			name = "";
		return functionMapper.selectLikeName(name.trim());
	}

	public Function selectById(String id) {
		return functionMapper.selectById(id);
	}

	public List<Function> selectByProcessKey(String processKey) {
		return functionMapper.selectByProcessKey(processKey);
	}
	
	public void logicDelete(String id) {
		functionMapper.logicDelete(id);
	}

	public void delete(String id) {
		functionMapper.delete(id);
	}
	
	/**字段检查
	 * @param function
	 */
	private void checkFunction(Function function) {
		if(CommonUtil.isEmpty(function.getFunctionName())){
			//方法名不能为空
		}else{
			if(function.getFunctionName().length()>64){
				//方法名最长64个字符
			}
			List<Function> list = functionMapper.selectByName(function.getFunctionName());
			if(CommonUtil.isNotEmpty(list)){
				for(Function f:list){
					if(CommonUtil.isNotEmpty(function.getId()) && !f.getId().equals(function.getId())){
						//方法名已存在
						break;
					}
				}
			}
		}
		if(CommonUtil.isEmpty(function.getExecUrl())){
			//方法执行路径不能为空
		}
	}


	public List<Function> findAll(){
		return functionMapper.selectAll();
	}
}
